<template>
  <div>
    <el-form
      :model="form"
      :rules="rules"
      label-width="100px"
      ref="form"
      class="kylin-form"
    >
      <el-form-item :label="$t('system.target_type')" prop="target_type">
        <el-select v-model="form.target_type" class="size">
          <el-option
            v-for="item in targets"
            :key="item.id"
            :value="item.id"
            :label="item.name"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        :label="$t('system.batch')"
        prop="batch"
        v-if="form.target_type === 'Batch'"
      >
        <el-select v-model="form.batch" class="size">
          <el-option
            v-for="item in batches"
            :key="item.id"
            :value="item.id"
            :label="item.name"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        :label="$t('system.host')"
        prop="host"
        v-if="form.target_type === 'Host'"
      >
        <virtual-list
          :value="form.host"
          :multiple="true"
          :obj="true"
          size="small"
          class="size"
          @selectValue="handleHostSelect"
          :list="hosts"
        ></virtual-list>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="handleCancel">{{ $t("cancel") }}</el-button>
      <el-button class="kylin-button" @click="handleRun">{{
        $t("run")
      }}</el-button>
    </div>
  </div>
</template>

<script>
import virtualList from "@/components/virtualList";
import { runScript, createScripts, checkScript } from "@/api/script";
import { getAgentList } from "@/api/system";
import { getBatchList } from "@/api/batch";
export default {
  components: {
    virtualList,
  },
  props: {
    scriptFrom: {
      default: null,
    },
    row_id: {
      default: null,
    },
    content: {
        default: ""
    }
  },
  data() {
    return {
      targets: [
        { id: "Batch", name: this.$t("system.batch") },
        { id: "Host", name: this.$t("system.host") },
      ],
      hosts: [],
      batches: [],
      form: {
        target_type: "Batch",
        batch: "",
        host: [],
      },
      rules: {
        batch: [
          {
            required: true,
            message: this.$t("system.batch_require"),
            trigger: "change",
          },
        ],
        host: [
          {
            required: true,
            message: this.$t("system.host_require"),
            trigger: "change",
          },
        ],
      },
    };
  },
  mounted() {
    getBatchList({ paged: false }).then((res) => {
      let results = res.data.data && res.data.data.results;
      let batches = [];
      results.forEach((item) => {
        batches.push({ id: item.id, name: item.name });
      });
      this.batches = batches;
    });
    getAgentList({ paged: false, sortBy: "ip", sortOrder: "asc" }).then(
      (res) => {
        let results = res.data.data && res.data.data.results;
        let hosts = new Set();
        results.forEach((item) => {
          hosts.add({ id: item.id, name: item.ip });
        });
        this.hosts = Array.from(hosts);
      }
    );
  },
  methods: {
    handleClose() {
      this.$refs.form.resetFields();
      this.$emit("click");
    },
    handleHostSelect(value) {
      this.form.host = value;
    },
    handleCancel() {
      this.$refs.form.resetFields();
      this.$emit("click");
    },
    handleRun() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          let data = { targetType: this.form.target_type };
          if (this.form.target_type == "Batch") {
            data["targetIds"] = [this.form.batch];
          } else {
            data["targetIds"] = this.form.host;
          }
          if (this.row_id && !this.scriptFrom) {
            data["id"] = this.row_id;
            data["verified"] = true;
            checkScript({ content: this.content }).then((res) => {
              let bol = res.data.data;
              if (bol) {
                runScript(data).then((res) => {
                  if (res.data.code == "0") {
                    this.$message({
                      type: "success",
                      message: res.data.message,
                    });
                    this.$emit("click");
                    if (res.data.data && res.data.data.id) {
                      this.$router.push({
                        name: "log_detail",
                        params: { id: res.data.data.id },
                      });
                    }
                  } else {
                    this.$message({
                      type: "error",
                      message: res.data.message,
                    });
                  }
                });
              } else {
                this.$confirm(
                  "该脚本存在危险命令，请确认是否要操作？",
                  "提示",
                  {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning",
                  }
                ).then(() => {
                  runScript(data).then((res) => {
                    if (res.data.code == "0") {
                      this.$message({
                        type: "success",
                        message: res.data.message,
                      });
                      this.$emit("click");
                      if (res.data.data && res.data.data.id) {
                        this.$router.push({
                          name: "log_detail",
                          params: { id: res.data.data.id },
                        });
                      }
                    } else {
                      this.$message({
                        type: "error",
                        message: res.data.message,
                      });
                    }
                  });
                });
              }
            });
          } else {
            checkScript({ content: this.scriptFrom.content }).then((res) => {
              let bol = res.data.data;
              if (bol) {
                createScripts({ ...data, ...this.scriptFrom }).then((res) => {
                  if (res.data.code == "0") {
                    this.$message({
                      type: "success",
                      message: res.data.message,
                    });
                    this.$emit("click");
                    this.$router.push({
                      name: "log_detail",
                      params: { id: res.data.data.id },
                    });
                  } else {
                    this.$message({
                      type: "error",
                      message: res.data.message,
                    });
                  }
                });
              } else {
                this.$confirm(
                  "该脚本存在危险命令，请确认是否要操作？",
                  "提示",
                  {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning",
                  }
                ).then(() => {
                  createScripts({ ...data, ...this.scriptFrom }).then((res) => {
                    if (res.data.code == "0") {
                      this.$message({
                        type: "success",
                        message: res.data.message,
                      });
                      this.$emit("click");
                      this.$router.push({
                        name: "log_detail",
                        params: { id: res.data.data.id },
                      });
                    } else {
                      this.$message({
                        type: "error",
                        message: res.data.message,
                      });
                    }
                  });
                });
              }
            });
          }
        }
      });
    },
  },
};
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.size {
  width: 100%;
}
</style>